//
//  ST_AIRecommendSearchedListController.swift
//  btvideo
//
//  Created by mac on 2020/7/7.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import MJRefresh
import SwiftyJSON
import SwiftyUserDefaults




//推荐特质 瀑布流 -Controller
class ST_AIRecommendSearchedListController: UIViewController, ST_PinterestHomeDataAdapterViewDelegate {
    
    fileprivate var first = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         
        
        view.addSubview(own_navigation_bar)
        own_navigation_bar.snp.makeConstraints { (make) in
            make.right.left.top.equalTo(view)
            make.height.equalTo(statusBarHeight+44)
        }
        
        
        let offset:CGFloat = (44-30)/2.0
        
        own_navigation_bar.addSubview(left_nav_btn)
        left_nav_btn.snp.makeConstraints { (make) in
            make.left.equalTo(own_navigation_bar).offset(15-offset)
            make.bottom.equalTo(own_navigation_bar)
            make.width.height.equalTo(44)
        }
        
        own_navigation_bar.addSubview(left_nav_btn)
        left_nav_btn.snp.makeConstraints { (make) in
            make.left.equalTo(own_navigation_bar).offset(15-offset)
            make.bottom.equalTo(own_navigation_bar)
            make.width.height.equalTo(44)
        }
        
        
        
        own_navigation_bar.addSubview(filter_btn)
        filter_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(44)
            make.right.equalToSuperview().offset(-15+offset)
            make.top.equalToSuperview().offset(statusBarHeight+7-offset)
        }
        
        own_navigation_bar.addSubview(title_nav_btn)
        title_nav_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(left_nav_btn)
            make.centerX.equalTo(own_navigation_bar)
        }
        
        own_navigation_bar.addSubview(searchBtn)
        searchBtn.snp.makeConstraints { (make) in
            make.left.equalTo(left_nav_btn.snp.right).offset(0)
            make.height.equalTo(38)
            make.centerY.equalTo(left_nav_btn)
            make.right.equalTo(filter_btn.snp.left).offset(-13+offset)
        }
        
        searchBtn.addSubview(textField)
        textField.snp.makeConstraints { (make) in
            make.edges.equalTo(searchBtn).inset(UIEdgeInsets.init(top: 1, left: 33, bottom: 0, right: 16+11+3))
        }
        
        searchBtn.addSubview(delete_btn)
        delete_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(16)
            make.centerY.equalTo(searchBtn)
            make.right.equalTo(searchBtn).offset(-11)
        }
        
        
        
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 44+statusBarHeight, left: 0, bottom: 0, right: 0))
        }
        
        self.collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.refresh_data()
        })
        
        self.adapter.delegate = self
        
        self.adapter.searchParam.removeAll()
        
        if !searchText.isEmpty{
            
            self.adapter.searchParam.updateValue(searchText, forKey: "search_name")
            
            self.adapter.searchParam.removeValue(forKey: "personal_want")
        }else{
            self.adapter.searchParam.removeValue(forKey: "search_name")
            self.adapter.searchParam.updateValue(seekValue, forKey: "personal_want")
            
        }
        
        
        self.refresh_data()
        
        NotificationCenter.default.addObserver(self, selector: #selector(like_ignore_hanlde(noti:)), name: Notification.Name.ignore_somebody, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(like_ignore_hanlde(noti:)), name: Notification.Name.ban_somebody, object: nil)
        
    }
    
    @objc fileprivate func refresh_data(){
        
        
        self.adapter.reloadData()
        
        self.play_scan_view()
        
    }
    
    func reload_view_from_data_adapter(currentCount:Int){
        
        
        
        self.stop_scan_view()
        
        self.collectionView.mj_header?.endRefreshing()
        self.collectionView.mj_footer?.endRefreshing()
        
        
        self.collectionView.footer_refresh(count: currentCount) {[weak self] in
            
            self?.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                
                self?.request_data()
            })
        }
        
        self.collectionView.reloadData()
    }
    
    
    func fail_load_data(code: Int, error: String) {
        
        ToastHud(text: error, view: self.view)
        
        self.collectionView.mj_header?.endRefreshing()
        self.collectionView.mj_footer?.endRefreshing()
        
    }
    
    @objc func refresh_data_from_remote(){
        
        clear_data()
        request_data()
    }
    
    @objc func clear_data(){
        
        self.adapter.clear_data()
        
    }
    
    @objc func like_ignore_hanlde(noti:Notification){
        
        //         ["accid": self.accid,"likeOption":true]
        let json = JSON.init(noti.userInfo ?? "")
        
        let accid = json["accid"].stringValue
        
        self.adapter.delete(itemId: accid)
        
    }
    
    //    MARK:- properties
    var searchText = ""
    
    var seekValue = 0
    
    lazy var own_navigation_bar:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.white
        return control
    }()
    
    
    //    MARK: - Filter
    fileprivate var home_filter_model: ST_PinterestHomeFilterModel?
    
    fileprivate lazy var filter_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("首页_icon_筛选")!)
        control.addTarget(self, action: #selector(filter_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var searchBtn:UIButton = {
        
        let control = ST_SearchButtonCreater.createSearchButton()
        
        control.isHidden = self.searchText.count < 1
        
        return control
    }()
    
    fileprivate lazy var delete_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("search_bar_delte")!)
        control.addTarget(self, action: #selector(clear_input_handle), for: UIControl.Event.touchUpInside)
        control.alpha = 0
        return control
    }()
    
    
    fileprivate lazy var textField:UITextField = {
        let control = UITextField()
        let attrString = NSMutableAttributedString(string: "请输入用户昵称")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.67, green: 0.7, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.attributedPlaceholder = attrString
        control.textColor = UIColor.init(hex: 0x333333)
        control.tintColor = UIColor.init(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.returnKeyType = .search
        control.enablesReturnKeyAutomatically = true
        control.delegate = self
        
        control.text = self.searchText
        return control
    }()
    
    
    fileprivate lazy var left_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImage(ST_ImageUtils.imageName("返回_gray"), for: UIControl.State.normal)
        
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
        
        //        control.backgroundColor = Color.random
        
        control.addTarget(self, action: #selector(left_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    fileprivate lazy var title_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setTitleColorForAllStates(Color.init(hexString: "#333333")!)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium)
        if let str = self.title{
            control.setTitleForAllStates(str)
            control.isHidden = false
        }else{
            control.isHidden = true
        }
        
        return control
    }()
    
    
    
    
    
    //    MARK:- properties
    
    fileprivate lazy var adapter:ST_PinterestHomeDataAdapter = {
        let d = ST_PinterestHomeDataAdapter()
        d.searchedResult = true
        return d
    }()
    
    fileprivate lazy var playerView:ST_PairsShareParticularView = {
        let control = ST_PairsShareParticularView()
        control.isUserInteractionEnabled = false
        control.cornerRadius = 20
        return control
    }()
    fileprivate lazy var transition = ST_PairsTransition()
    
    fileprivate lazy var layout:ST_CHTCollectionViewWaterfallLayout = {
        let controlLayout = ST_CHTCollectionViewWaterfallLayout()
        controlLayout.minimumColumnSpacing = ST_PinterestHomeCellMinimumColumnSpacing
        controlLayout.minimumInteritemSpacing = 10
        controlLayout.sectionInset = UIEdgeInsets.init(top: 10, left: 10, bottom: BTSafeAreaBottom, right: 10)
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = Color.white
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_PinterestHomeCell.self)
        control.register(cellWithClass: PinterestGuidanceHomeCell.self)
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 49, right: 0)
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        control.emptyDataSetSource = self
        
        control.emptyDataSetDelegate = self
        return control
    }()
    
    
    fileprivate lazy var containerRect = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
    
    
    
    
    //    MARk: - scan UI
    
    fileprivate func stop_scan_view(){
        
        scan_root_view.isHidden = true
        scan_animate_view.stop()
        
    }
    
    fileprivate func play_scan_view(){
        
        if scan_root_view.superview == nil{
            view.insertSubview(scan_root_view, aboveSubview: collectionView)
            scan_root_view.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            
            
            scan_root_view.addSubview(scan_animate_view)
            scan_animate_view.snp.makeConstraints { (make) in
                make.width.height.equalTo(50/375.0*ScreenWidth)
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview()
            }
        }
        scan_root_view.isHidden = false
        scan_animate_view.play()
    }
    
    
    
    fileprivate lazy var scan_root_view:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.white
        return control
    }()
    
    fileprivate lazy var scan_animate_view:LOTAnimationView = {
        
        let path = Bundle.main.path(forResource: "homeSearchAnimation", ofType: "json")!
        
        let control = LOTAnimationView.init(filePath: path)
        
        control.contentMode = UIView.ContentMode.scaleAspectFill
        
        control.loopAnimation = true
        
        return control
    }()
}


extension ST_AIRecommendSearchedListController:UITextFieldDelegate{
    
    @objc fileprivate func clear_input_handle(){
        textField.text = nil
        self.text_did_change_handle()
        
        
        self.navigationController?.popViewController(animated: false)
        
    }
    
    @objc fileprivate func text_did_change_handle(){
        delete_btn.alpha = (textField.text?.isEmpty ?? true) ? 0 : 1
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        
        delete_btn.alpha = (textField.text?.isEmpty ?? true) ? 0 : 1
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        guard let str = textField.text,!str.isEmpty else {
            return true
        }
        
        searchText = str
        
        if !searchText.isEmpty{
            self.adapter.searchParam.updateValue(searchText, forKey: "search_name")
        }
        
        
        self.refresh_data_from_remote()
        
        
        return true
    }
    
}

extension ST_AIRecommendSearchedListController{
    
    @objc fileprivate func left_click(){
        
        if searchText.isEmpty{
            
            goback_previous_controller()
            
        }else{
            
            self.navigationController?.dismiss(animated: false, completion: nil)
        }
        
    }
    
    @objc func filter_handle()  {
        
        let vc = ST_AIRecommendAdvanceFIlterController(filterModel: self.home_filter_model)
        
        vc.refresh_closure = {[weak self] pm in
            
            
            guard let strongSelf = self else{
                return
            }
            
            self?.home_filter_model = pm
            
            self?.adapter.searchParam = pm.conver_to_param()
            
            if !strongSelf.searchText.isEmpty{
                self?.adapter.searchParam.updateValue(strongSelf.searchText, forKey: "search_name")
            }else{
                
                self?.adapter.searchParam.updateValue(strongSelf.seekValue, forKey: "personal_want")
                
            }
            self?.adapter.reloadData()
        }
        
        let home_filter_navigation_controller =  UINavigationController.create_hiding_bar_navigation_controller(rootViewController: vc)
        
        home_filter_navigation_controller.overCurrentContext = true
        
        GlobalPresent(toController: home_filter_navigation_controller)
        
    }
}



//MARK: - Request Data
extension ST_AIRecommendSearchedListController{
    
    fileprivate func request_data(){
        
        if self.adapter.currentPage == 0{
            play_scan_view()
        }
        
        self.adapter.load_data_from_remote()
        
    }
    
}


extension ST_AIRecommendSearchedListController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
        
        if first{
            self.first = false
            return false
        }else{
            return true
        }
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        
        let attrString = NSMutableAttributedString(string: "没有找到相关用户或特质呢")
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        
        return ST_ImageUtils.imageName("首页_img_活跃(空)")
    }
}

extension ST_AIRecommendSearchedListController:CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource{
    
    /*
    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        if let last = current_play_index_path,last.row == indexPath.row{
            self.pause_video()
        }
    }
    */
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return self.adapter.data_array[safe:indexPath.item]?.size ?? CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.adapter.data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let m = self.adapter.data_array[indexPath.item]
        
        if m.type.rawValue > 1{
            
            let cell = collectionView.dequeueReusableCell(withClass: PinterestGuidanceHomeCell.self, for: indexPath)
            
            cell.bind_model(m)
            
            return cell
        }
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_PinterestHomeCell.self, for: indexPath)
        
        cell.model = m
        
        cell.ignore_somebody_closure = { [weak self] id , str in
            self?.ignore(userId: id, notice: str)
        }
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        //        查看活跃的人 或者 查看新人
        if let cell = self.collectionView.cellForItem(at: indexPath) as? PinterestGuidanceHomeCell,cell.guidanceType != .normal{
            //             查看活跃的人
            if cell.guidanceType == .active{
                self.navigationController?.pushViewController(PinterestActiveViweController())
            }
                //          查看新人
            else if cell.guidanceType == .join{
                self.navigationController?.pushViewController(ST_PinterestNewGirlsViewController())
            }
            return
        }
        
        
        guard  let item = self.adapter.data_array[safe:indexPath.item] else{return}
        
        //        判断引导
        if item.type.rawValue > 1{
            
        }else{
            self.present_detail(item: item, indexPath: indexPath)
        }
        
    }
    
    
    
    func scroll_to_top_by_main_btn(){
        
        self.collectionView.setContentOffset(CGPoint.zero, animated: true)
        
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        playerView.removeFromSuperview()
        
    }
    
    /*
     fileprivate func pause_video(){
     
     if playerView.superview == nil {
     return
     }
     
     if playerView.frame.width == ScreenWidth{
     return
     }
     
     playerView.clear_data()
     
     playerView.removeFromSuperview()
     }
     */
}


//MARK: - Event
extension ST_AIRecommendSearchedListController{
    
    
    
    func ignore(userId:String,notice:String){
        
        IgnoreBehavior(userId: userId) { (f, err) in
            
            if f{
                
                ToastHud(text: notice, view: self.view)
                
                main_thread_execute(afterDelay: 1.6) {
                    
                    self.adapter.delete(itemId: userId)
                    
                }
                
            }else{
                self.toast(text: err)
            }
            
        }
        
        
    }
    
    func refresh_guidance_status(){
        
        
        main_thread_execute {
            
            self.collectionView.visibleCells.forEach { (cell) in
                
                guard let iCell = cell as? PinterestGuidanceHomeCell else{return}
                
                iCell.refresh_guidance_status()
                
            }
        }
    }
    
}

//MARK: - 跳转详情
extension ST_AIRecommendSearchedListController:ST_PairsTransitionProtocol{
    
    
    func present_detail(item:ST_PinterestHomeCellModel,indexPath:IndexPath) {
        
        guard let currCell = collectionView.cellForItem(at: indexPath) as? ST_PinterestHomeCell else{
            return
        }
        
        playerView.clear_data()
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = item.accid
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
//        playerView.setUp(data_array: item.resourceList)
//
////        playerView.rightSignLabel.isHidden = !item.is_new_user
//
//
//
//        let rectInScreen = currCell.convert(currCell.picutreframe_in_content_view(), to: nil)
//
//        playerView.present_start_rect = rectInScreen
//        playerView.present_start_idx = indexPath
//        playerView.fromeController = self
//
//
//        self.adapter.currPairsUserId = item.accid
//
//        let vc = ST_InteractivePairsCenterController.init(album: item.resourceList, accid: item.accid, sign: item.sign, home_pushed: true, data_adapter: self.adapter)
//
//        self.adapter.currPairsUserId = item.accid
//
//        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
//
//        transition.operationView = self.playerView
//
//        nav.transitioningDelegate = transition
//
//        nav.modalPresentationStyle = .custom
//
//        self.present(nav, animated: true, completion: nil)
//        
    }
    
    func present_start_cell()->UICollectionViewCell?{
        
        guard let idx = playerView.present_start_idx  else {
            return nil
        }
        
        return self.collectionView.cellForItem(at: idx)
        
    }
    
    
}


